package com.evil.kingdom.service.base;

import com.evil.common.core.util.StreamUtil;
import com.evil.kingdom.pojo.dto.person.base.PersonTypeDto;
import com.evil.kingdom.pojo.entity.person.base.Person;
import com.evil.kingdom.pojo.enums.PersonTypeEnum;
import com.evil.kingdom.service.person.base.PersonService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 人物类型
 *
 * @author liyang
 * @date 2024-06-04 18:33
 */
@Slf4j
@Service
@AllArgsConstructor
public class PersonTypeStrategy {

    private final PersonService personService;
    private final List<PersonTypeService<?, ?>> personTypeServices;

    public Optional<PersonTypeDto> isExistDtoByName(String name) {
        return personService.isExistByName(name).flatMap(person -> this.calPersonType(person).isExistDtoByPerson(person));
    }

    public PersonTypeDto findDtoByName(String name) {
        Person person = personService.findByName(name);
        return this.calPersonType(person).findDtoByPerson(person);
    }

    private PersonTypeService<?, ?> calPersonType(Person person) {
        PersonTypeEnum personTypeEnum = PersonTypeEnum.findByType(person.getType());
        return StreamUtil.isExistFirst(personTypeServices, s -> s.type() == personTypeEnum).orElseThrow(PersonTypeEnum::error);
    }
}
